<template>
    <layout>
        <div class='wrapper'>
            <van-cell-group class="info">
                <van-cell title="成团人数：" :value="info.userMin"></van-cell>
                <van-cell title="截至日期：" :value="info.endTime"></van-cell>
                <van-cell title="拼团码：" :value="info.collageNo"></van-cell>
                <van-cell title="拼团发起人：" :value="info.linkMan"></van-cell>
                <van-cell title="发起地址：" :value="info.address"></van-cell>
                <van-cell title="采样时间：" :value="info.applyTime"></van-cell>
                <van-cell title="单价：" :value="info.itemPrice"></van-cell>
            </van-cell-group>

            <van-form class="form" @submit="onSubmit">
                <van-field
                    name="joinName"
                    label="姓名"
                    v-model.trim="formData.joinName"
                    clearable
                    required
                    placeholder="请输入姓名"
                    @input="ValidateValue"
                    :rules="[{required:true,message:'请输入姓名'}]"
                    >

                </van-field>
                <van-field
                    name="joinPhone"
                    label="手机号"
                    v-model="formData.joinPhone"
                    clearable
                    required
                    placeholder="请输入手机号"
                    :rules="[{ required: true, message: '请填写手机号' },{pattern:/^\d{11}$/,message:'手机号格式错误'}]"
                    >
                </van-field>
                <van-field
                    name="groupNumber"
                    label="检验人数"
                    v-model="formData.groupNumber"
                    clearable
                    required
                    clear-trigger="always"
                    placeholder="请选择检验人数"
                    @click="numberPickerVisible = true"
                    :rules="[{required:true,message:'请选择检验人数'}]">

                </van-field>
                <van-field
                    name="price"
                    label="预计价格"
                    :value="priceInput"
                    readonly
                    >

                </van-field>
                <van-field
                    type="textarea"
                    rows="2"
                    autosize
                    show-word-limit
                    maxlength="20"
                    name="joinAddress"
                    label="详细地址"
                    v-model="formData.joinAddress"
                    required
                    placeholder="请输入详细地址"
                    :rules="[{required:true,message:'请输入详细地址'}]">

                </van-field>
                <div class="btn">
                    <van-button type="info" block round native-type="submit">加入拼团</van-button>
                </div>
            </van-form>
        </div>

        <!--  人数选择弹框  -->
        <van-popup v-model="numberPickerVisible" position="bottom" round>
            <van-picker
                title="选择人数"
                :columns="numberList"
                @confirm="confirmNumber"
                @cancel="numberPickerVisible=false"
                show-toolbar
                >

            </van-picker>
        </van-popup>
    </layout>
    
</template>

<script>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// 例如：import 《组件名称》 from '《组件路径》';
import nucleicApi from '@/api/nucleic'
import groupJoinApi from "@/api/groupJoin"
export default {
// import引入的组件需要注入到对象中才能使用
  components: {},
  data  () {
// 这里存放数据
    return {
        openId:"",
        collageId:"",
        numberPickerVisible:false,
        numberList:["",1,2,3,4,5,6,7,8,9,10],
        info:{
            userMin:"",
            endTime:"",
            collageNo:"",
            linkMan:"",
            address:"",
            applyTime:"",
            itemPrice:"",
        },
        formData:{
            collageId:"",
            joinName:"",
            joinPhone:"",
            groupNumber:"",
            price:"",
            joinAddress:"",
        }
    }
  },
// 监听属性 类似于data概念
  computed: {
    prices(){
        let value = this.formData.price*this.formData.groupNumber
        return value?value:""
    },
    priceInput(){
        return this.formData.price+"元/人"+"-总计："+this.prices+"元"
    }
  },
// 监控data中的数据变化
  watch: {},
// 方法集合
  methods: {
    init(){
            this.collageId = this.$route.query.state
            this.getcollageInfo()
            this.getOpenId()
    },
    // 获取openId
    getOpenId(){
        let params = {
            id:this.$route.query.code||false
        }
        nucleicApi.getOpenId(params).then(res=>{
            if(res.status==0){
                if(res.data){
                    this.openId = res.data
                }else{
                    this.$dialog.alert({
                        title:"提示",
                        message:"请退出页面，重新进入，否者此次申请无效！"
                    }).then(res=>{
                        window.close();
                        WeixinJSBridge.call('closeWindow');
                    })
                    return;
                }
            }else{
                this.$dialog.alert({
                    title:"提示",
                    message:res.msg
                })
            }
        })
    },
    // 获取拼团信息
    getcollageInfo(){
        let params = {
            id:this.collageId||false
        }
        groupJoinApi.getCollageInfo(params)
            .then(res=>{
                if(res.status==0){
                    if(res.data){
                        this.info.userMin = res.data.userMin
                        this.info.endTime = res.data.endTime
                        this.info.collageNo = res.data.collageId
                        this.info.linkMan = res.data.linkMan
                        this.info.address = res.data.address
                        this.info.applyTime = res.data.applyTime
                        this.info.itemPrice = res.data.itemPrice
                        this.formData.collageId = res.data.collageId
                        this.formData.price = res.data.itemPrice
                    }else{
                        this.$toast({
                            type:"fail",
                            message:"页面加载失败请重试"
                        })
                    }
                    
                }else{
                    this.$dialog.alert({
                        title:"提示",
                        message:res.msg
                    })
                }
            })
    },
    confirmNumber(value){
        this.formData.groupNumber = value
        this.numberPickerVisible = false
    },
    onSubmit(){
        // 去空格
        this.formData.joinName = this.formData.joinName.replace(/\s/g,"")
        let params = {
            collageId:this.formData.collageId,
            userNum:this.formData.groupNumber,
            itemPrice:this.formData.price,
            payAmount:this.prices,
            address:this.formData.joinAddress,
            openId:this.formData.openId,
            linkMan:this.formData.joinName,
            linkphone:this.formData.joinPhone,
        }
        groupJoinApi.addCollagePlayer(params)
            .then(res=>{
                if(res.status==0){
                    this.wxToPay(res.data);
                }else{
                    this.$dialog.alert({
                        title:"提示",
                        message:res.msg
                    })
                }
            })
            .catch(err=>{
                this.$dialog.alert({
                    title:"错误",
                    message:err
                })
            })
    },
    wxToPay(collagePayId) {
        var _this = this
        let params = {
            applyId: Number(collagePayId),
            actualPay: Number(_this.prices),
            payType: 1,
        }
        groupJoinApi.collagePay(params)
            .then(res=>{
                if(res.status==0){
                    let payConfig = res.data
                    WeixinJSBridge.invoke(
                        'getBrandWCPayRequest', {
                            "appId":payConfig.appId,     //公众号ID，由商户传入
                            "timeStamp":payConfig.timeStamp,         //时间戳，自1970年以来的秒数
                            "nonceStr":payConfig.nonceStr, //随机串
                            "package":payConfig.package,
                            "signType":payConfig.signType,         //微信签名方式
                            "paySign":payConfig.paySign //微信签名
                        },
                        function(res){
                            //alert(res.err_msg);
                            if(res.err_msg == "get_brand_wcpay_request:ok"){
                                // 使用以上方式判断前端返回,微信团队郑重提示：
                                //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
                                //window.open("/group_invitation.html?id="+collagePayId)
                                _this.$dialog.alert({
                                    title:"提示",
                                    message:"支付成功",
                                })
                                // alert("支付成功");
                                _this.$router.push({
                                    path:"groupPayInfo",
                                    query:{
                                        id:collagePayId
                                    }
                                })
                                // window.open("./group_payInfo.html?id="+collagePayId)
                                // 成功了 跳转到详情页
                            }else if(res.err_msg == "get_brand_wcpay_request:cancel"){
                                // 提示用户取消了二维码支付
                                _this.deleteApply(collagePayId);
                                _this.$dialog.alert({
                                    title:"提示",
                                    message:"用户取消了支付",
                                })
                                // alert("用户取消了支付");
                                return
                            }else if(res.err_msg == "get_brand_wcpay_request:fail"){
                                // 提示支付失败
                                _this.deleteApply(collagePayId);
                                _this.$dialog.alert({
                                    title:"提示",
                                    message:"支付失败，请重新发起拼团",
                                })
                                // alert("支付失败，请重新发起拼团");
                            }
                        });
                }else{
                    _this.$dialog.alert({
                        title:"提示",
                        message:res.msg
                    })
                }
            })
            .catch(err=>{
                _this.$dialog.alert({
                    title:"错误",
                    message:err
                })
            })
        // $.ajax({
        //     //请求方式
        //     type:"POST",
        //     //文件位置
        //     url:"https://wxapi.kanglailab.com/wx/v1/collage/pay",
        //     contentType: "application/json",
        //     dataType: "json",
        //     data:JSON.stringify(param),
        //     //请求成功后要执行的函数，拼接html
        //     success: function(ret){
        //         if (ret.status == 0){
        //             var payConfig = ret.data;
        //             WeixinJSBridge.invoke(
        //                 'getBrandWCPayRequest', {
        //                     "appId":payConfig.appId,     //公众号ID，由商户传入
        //                     "timeStamp":payConfig.timeStamp,         //时间戳，自1970年以来的秒数
        //                     "nonceStr":payConfig.nonceStr, //随机串
        //                     "package":payConfig.package,
        //                     "signType":payConfig.signType,         //微信签名方式
        //                     "paySign":payConfig.paySign //微信签名
        //                 },
        //                 function(res){
        //                     //alert(res.err_msg);
        //                     if(res.err_msg == "get_brand_wcpay_request:ok"){
        //                         // 使用以上方式判断前端返回,微信团队郑重提示：
        //                         //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
        //                         //window.open("/group_invitation.html?id="+collagePayId)
        //                         alert("支付成功");
        //                         window.open("./group_payInfo.html?id="+collagePayId)
        //                         // 成功了 跳转到详情页
        //                     }else if(res.err_msg == "get_brand_wcpay_request:cancel"){
        //                         // 提示用户取消了二维码支付
        //                         deleteApply(collagePayId);
        //                         alert("用户取消了支付");
        //                         return
        //                     }else if(res.err_msg == "get_brand_wcpay_request:fail"){
        //                         // 提示支付失败
        //                         deleteApply(collagePayId);
        //                         alert("支付失败，请重新发起拼团");
        //                     }
        //                 });

        //         }else{
        //             alert(ret.msg);
        //             return;
        //         }
        //     },error: function (xhr, status, p3, p4) {
        //         var err = "Error " + " " + status + " " + p3;
        //         if (xhr.responseText && xhr.responseText[0] == "{")
        //             err = JSON.parse(xhr.responseText).message;
        //         alert(err);
        //     }
        // });
    },
    deleteApply(collagePayId) {
        var params = {
            id: Number(collagePayId),
            state: -1
        }
        groupJoinApi.delCollagePay(params)
            .then(res=>{
                if(res.status!=0){
                    this.$dialog.alert({
                        title:"提示",
                        message:res.msg,
                    })
                }
            })
    },
    ValidateValue() {
        var IllegalString = "[`~!#$^&*()=|{}':;',\\[\\].<>/?~！#￥……&*（）——|{}【】‘；：”“'。，、？123456789]“”";
        var index = this.formData.joinName.length - 1;
        var s = this.formData.joinName.charAt(index);
        if (IllegalString.indexOf(s) >= 0) {
            s = this.formData.joinName.substring(0, index);
            this.formData.joinName = s;
        }
    
    },
  },
// 生命周期 - 创建完成（可以访问当前this实例）
  created  () {

  },
// 生命周期 - 挂载完成（可以访问DOM元素）
  mounted  () {
    this.init()
  },
  beforeCreate  () {}, // 生命周期 - 创建之前
  beforeMount  () {}, // 生命周期 - 挂载之前
  beforeUpdate  () {}, // 生命周期 - 更新之前
  updated  () {}, // 生命周期 - 更新之后
  beforeDestroy  () {}, // 生命周期 - 销毁之前
  destroyed  () {}, // 生命周期 - 销毁完成
  activated  () {} // 如果页面有keep-alive缓存功能，这个函数会触发
}
</script>
<style lang="less" scoped>
    .wrapper{
        width: 93%;
        margin: auto;
        
        .info,.form{
            margin: 20px 0;
            border-radius: 10px;
            background-color: white;
            box-shadow: 0 0 12px rgba(0,0,0,10%);
            overflow: hidden;
            .btn{
                padding: 20px;
            }
        }
    }
</style>